package ClientLoginOrder

import (
	LogUtils "IMServices/LogService"
	"IMServices/LoginService/LoginOrder"
	"IMServices/NetIO/Packet"
	"IMServices/NetIO/ServiceNetIO"
	"bytes"
	"encoding/binary"
	"fmt"
	"io"
	"net"
)

func LoginHandle(pack Packet.MessageRequest, conn net.Conn) {
	headerLength := pack.MsgHeader.HeaderLength
	packetLength := pack.MsgHeader.PacketLength
	bodyLength := packetLength - headerLength
	fmt.Println(bodyLength)
	//var loginDefine LoginDefine

	//解析登录包【login-body】

	buf := &bytes.Buffer{}
	err := binary.Write(buf, binary.BigEndian, pack.MsgHeader)
	if err != nil {
		return
	}

	request := ServiceNetIO.RequestBuffer{
		TargetServer: "StatusServer",
		Request: ServiceNetIO.MessageRequest{
			Header:     buf.Bytes(),
			ServerName: "LoginServer",
			OrderId:    1,
			EncodeType: "",
			Body:       pack.MsgBody,
		},
	}
	ServiceNetIO.AddNewMessage(request)

	//newRequest := &ServiceNetIO.NewMessageRequest{
	//	Header:     buf.Bytes(),
	//	ServerName: "LoginServer",
	//	OrderId:    0,
	//	EncodeType: "",
	//	Body:       pack.MsgBody,
	//}
	//send2Server(ServiceNetIO.ServerTypeStatus, newRequest)

	//返回包
	//_, err = conn.Write(pack.MsgBody)
	//if err != nil {
	//	return
	//}
}

func send2Server(serverType int, newRequest *ServiceNetIO.NewMessageRequest) {
	var stream ServiceNetIO.UserServiceInterface_NewNotifyClient
	var err error
	if serverType == ServiceNetIO.ServerTypeStatus {
		if LoginOrder.Server.StatusServer.Client == nil {
			println("服务器未连接")
			return
		}
		stream, err = LoginOrder.Server.StatusServer.Client.NewNotify(LoginOrder.Server.StatusServer.Ctx)
	} else if serverType == ServiceNetIO.ServerTypeMessage {
		if LoginOrder.Server.MessageServer.Client == nil {
			println("服务器未连接")
			return
		}
		stream, err = LoginOrder.Server.MessageServer.Client.NewNotify(LoginOrder.Server.MessageServer.Ctx)
	}

	if err != nil {
		LogUtils.LogError("failed to call YourMethod: %v", err)
	}

	if err = stream.Send(newRequest); err != nil {
		LogUtils.LogError("Error sending message: %v", err)
	}
	//LogUtils.LogInfo("Sent message to server: %v", req)

	_, err = stream.Recv()
	if err == io.EOF {
		LogUtils.LogError("Server closed stream")
		return
	}
}
